/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {boolean}
 */
class Node {
  constructor (key) {
    this.key = key
    this.left = null
    this.right = null // 右节点
  }
}
// 二叉树:左子树系节点值 <根节点 右子树节点值 大于跟界节点
/// 封装二叉搜索树
class binarySearchTree {
  constructor () {
    this.root = null // 根节点
  }
  // 插入数据
  insert(value) {
    const newNode = new Node(value);
    
    if (this.root === null) {
      this.root = newNode;
    } else {
      this.insertNode(this.root, newNode);
    }
  }

  insertNode(node, newNode) {
    if (newNode.value < node.value) {
      if (node.left === null) {
        node.left = newNode;
      } else {
        this.insertNode(node.left, newNode);
      }
    } else {
      if (node.right === null) {
        node.right = newNode;
      } else {
        this.insertNode(node.right, newNode);
      }
    }
  }
  //先序遍历
  preorderTraversal () {
    let result = []
    this.preorderTraversalNode(this.root, result)
    return result
  }
  preorderTraversalNode (node, result) {
    if (node === null) return
    result.push(node.key)
    this.preorderTraversalNode(node.left, result)
    this.preorderTraversalNode(node.right, result)
  }
  // 中序遍历 先遍历左节点树 再根节点 再又右节点数
  inorderTraversal () {
    let result = []
    this.inorderTraversalNode(this.root, result)
    return result
  }
  inorderTraversalNode (node, result) {
    if (node === null) return
    this.inorderTraversalNode(node.left, result)
    result.push(node.key)
    this.inorderTraversalNode(node.right, result)
  }
  // 后序遍历 左右根
  postorderTraversal () {
    let result = []
    this.postorderTraversalNode(this.root, result)
    return result
  }
  postorderTraversalNode (node, result) {
    if (node === null) return
    this.postorderTraversalNode(node.left, result)
    this.postorderTraversalNode(node.right, result)
    result.push(node.key)
  }
  // 查找二叉搜索树的最小最大值
  min () {
    if (this.root === null) return null
    let node = this.root
    while (node.left !== null) {
      node = node.left
    }
    return node.key
  }
  max () {
    if (this.root === null) return null
    let node = this.root
    while (node.right !== null) {
      node = node.right
    }
    return node.key
  }
}
var isSameTree = function(p, q) {

};
let p = new binarySearchTree()
p.insert(1)
p.insert(2)
p.insert(3)
console.log(p);